package com.bphx.android.activities;

import android.os.Bundle;
import android.view.ViewGroup;
import com.bphx.android.IStorage;
import com.bphx.android.activities.dialogs.ErrorDialog;
import com.bphx.android.activities.views.RemovableEditText;
import com.bphx.android.db.Storage;
import com.bphx.android.exception.BaseException;
import com.bphx.android.ui.ITextView;
import com.bphx.android.words.Word;

import java.util.List;

import static com.bphx.android.utils.Constants.ORIGINAL_WORD_KEY;
import static com.bphx.android.utils.Constants.WORD_KEY;
import static org.apache.commons.lang.StringUtils.isNotBlank;

/**
 * @author Vyacheslav Kovalyov
 * @version 1.0
 */
public class EditWordActivity extends CreateWordActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        originalWord = (Word) getIntent().getExtras().get(WORD_KEY);
        initForm(originalWord);
    }

    @Override
    protected void dispatchOk() {
        IStorage storage = new Storage(this);

        try {

            Word word = createWord();
            storage.replaceWord(word, originalWord);

            getIntent().putExtra(WORD_KEY, word);
            getIntent().putExtra(ORIGINAL_WORD_KEY, word);
            setResult(RESULT_OK, getIntent());
            finish();
        } catch (BaseException e) {

            new ErrorDialog(this, e.getMessage()).show();
        }
    }

    private void initForm(Word word) {
        if (word == null) {
            return;
        }

        originalWordField.setText(word.getOriginalWord());

        initVariants(variants, word.getVariants(), variantsLayout);
        initVariants(invalidVariants, word.getInvalidTranslations(), invalidVariantsLayout);
    }

    private void initVariants(List<ITextView> variants,
                              List<String> variantsList, ViewGroup layout) {

        for (String s : variantsList) {
            if (isNotBlank(s)) {

                RemovableEditText et = new RemovableEditText(this, this);
                et.setText(s);

                layout.addView(et);
                variants.add(et);
            }
        }
    }

    private Word originalWord;
}